package com.itaming.lycheeframework.support.cipher.symmetric;

import com.itaming.lycheeframework.support.cipher.CipherConstant;
import org.springframework.util.Assert;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * DES加密器
 *
 * @author A.Ming
 */
public class DesEncryptor extends AbstractSymmetricEncryptor {

    /**
     * 获取初始化向量长度，单位：bit
     *
     * @return 初始化向量长度
     */
    @Override
    protected int getIvBitLength() {
        return CipherConstant.DES_IV_BIT_LENGTH;
    }

    /**
     * 获取SecretKey
     *
     * @param key          密钥
     * @param keyBitLength 密钥长度(bit)
     * @return SecretKey
     */
    @Override
    protected SecretKey getSecretKey(String key, int keyBitLength) throws Exception {
        Assert.isTrue(keyBitLength == 64, "DES secret key must be 64 bit");
        SecretKeyFactory factory = SecretKeyFactory.getInstance(CipherConstant.ALGORITHM_DES);
        return factory.generateSecret(new DESKeySpec(getKeyBytes(key, keyBitLength)));
    }

}
